package com.niiwoo.civet.trade.service.local.refund;

import com.alibaba.dubbo.rpc.RpcContext;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.asset.dto.mq.R360OrderStatusChangedDTO;
import com.niiwoo.asset.enums.r360.R360OrderProjectSubStatusEnum;
import com.niiwoo.asset.enums.r360.R360OrderStatusEnum;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.dto.common.TradeBatchTransOrderDTO;
import com.niiwoo.civet.trade.dto.request.blacklist.BlackListStorageMQDTO;
import com.niiwoo.civet.trade.dto.request.databackflow.ProjectStatusChangeBackFlowRequestDTO;
import com.niiwoo.civet.trade.enums.BatchRefundTypeEnum;
import com.niiwoo.civet.trade.enums.ProjectFromSourceEnum;
import com.niiwoo.civet.trade.enums.ProjectSubStatusEnum;
import com.niiwoo.civet.trade.service.local.activity.ActivityEventService;
import com.niiwoo.civet.trade.service.local.databackflow.TianChengDataBackFlowLocalService;
import com.niiwoo.civet.trade.service.local.project.ProjectLocalService;
import com.niiwoo.civet.trade.service.local.third.AegisLocalService;
import com.niiwoo.civet.trade.service.local.third.TianChengLocalService;
import com.niiwoo.civet.trade.utils.RepaymentUtil;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 配账相关服务
 * Created by bincun on 2017/11/9.
 */
@Slf4j
@Service
public class TransDetailLocalService {
    @Autowired
    private ProjectMapperExt projectMapperExt;
    @Autowired
    private PrivacyMasks privacyMasks;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ProjectLocalService projectLocalService;
    @Autowired
    private TianChengLocalService tianChengLocalService;
    @Autowired
    private AegisLocalService aegisLocalService;
    @Autowired
    private ActivityEventService activityEventService;
    @Autowired
    private TianChengDataBackFlowLocalService tianChengDataBackFlowLocalService;

    /**
     * 资金端 处理标的状态
     * 自动处理黑灰名单
     * @param dtoSrc
     * @param refundDate
     * @param
     */
    public void handleProjectStatus4Fund(TradeBatchTransOrderDTO dtoSrc,DateTime refundDate){
        if (RepaymentUtil.getOverdueDay(dtoSrc.getRefundDate(), new Date()) > 0 ) {
            log.info("---handleProjectStatus=--overdue---projectId={}",dtoSrc.getProjectId());
            // 更新标的状态为逾期还款中
            projectLocalService.updateProjectStatusToOverdue4Fund(dtoSrc.getProjectId());
            // 天秤回流
            tianChengLocalService.handleTianChengRefund4Fund(dtoSrc, refundDate);
            //发送消息到神盾后台
            aegisLocalService.sendOverDueMqMsgToApp(dtoSrc);
            //发送消息到活动
            activityEventService.sendOverDueMqMsgToActivity(dtoSrc);
            //黑灰名单处理
            this.handleProjectToBlacklist(dtoSrc);
            //通知R360
            this.sendToR360MQ(dtoSrc.getProjectId(),R360OrderStatusEnum.OVER_DATE);
            try {
                //天称标的状态回流(逾期)
                RpcContext.getContext().asyncCall(() -> sendOverdueProjectStatus2TianCheng(dtoSrc.getProjectId()));
            } catch (Exception e) {
                log.error("标的状态变更事件回流(逾期),标的ID={},发生系统异常,原因={}", dtoSrc.getProjectId(), e);
            }
        }
        if (RepaymentUtil.getOverdueDay(refundDate.plusMonths(1).toDate(), new Date()) > 0) {
            log.info("---handleProjectStatus=--bad---projectId={}",dtoSrc.getProjectId());
            // 更新标的状态为坏账还款中
            projectLocalService.updateProjectStatusToBad4Fund(dtoSrc.getProjectId());

        }
    }

    /**
     * 通知R360
     * @param
     */
    public void sendToR360MQ(Long projectId,R360OrderStatusEnum r360OrderStatusEnum){
        try {
            if (!HintManagerHolder.isMasterRouteOnly()) {
                HintManagerHolder.clear();
                HintManager hintManager = HintManager.getInstance();
                hintManager.setMasterRouteOnly();
            }
            Project project = projectMapperExt.selectByPrimaryKey(projectId);

            if (project.getFromSource().equals(ProjectFromSourceEnum.R360.getType())) {
                log.info("r360通知发送,projectId={}", project.getProjectId());
                R360OrderStatusChangedDTO r360OrderStatusChangedDTO = new R360OrderStatusChangedDTO();
                r360OrderStatusChangedDTO.setProjectId(project.getProjectId());
                r360OrderStatusChangedDTO.setUpdateDate(new Date());
                r360OrderStatusChangedDTO.setR360OrderStatusEnumCode(r360OrderStatusEnum.getCode());
                r360OrderStatusChangedDTO.setR360OrderProjectSubStatusEnum(R360OrderProjectSubStatusEnum.enumOf(project.getSubStatus()));
                rabbitTemplate.convertAndSend("asset_exchange", "asset_exchange.order_status_nofify_for_common",
                        r360OrderStatusChangedDTO);
            }
        }catch (Exception e){
            log.error("send to r360 failed.",e);
        }
    }

    /**
     * 逾期标的状态变更天称回流
     *
     * @param projectId
     */
    public void sendOverdueProjectStatus2TianCheng(Long projectId) {
        try {
            ProjectStatusChangeBackFlowRequestDTO projectStatusChangeBackFlowRequestDTO = new ProjectStatusChangeBackFlowRequestDTO();
            projectStatusChangeBackFlowRequestDTO.setFromStatus(String.valueOf(ProjectSubStatusEnum.REPAYING_INIT.getSubStatus()));
            projectStatusChangeBackFlowRequestDTO.setStatus(String.valueOf(ProjectSubStatusEnum.REPAYING_OVERDUE.getSubStatus()));
            projectStatusChangeBackFlowRequestDTO.setProjectId(projectId);

            RpcContext.getContext().asyncCall(() -> tianChengDataBackFlowLocalService.projecctStatusChange(projectStatusChangeBackFlowRequestDTO));
        } catch (Exception e) {
            log.error("标的状态变更事件回流,标的ID={},发生系统异常,原因={}", projectId, e);
        }
    }

    /**
     * 逾期30天及以上，入黑名单
     * 逾期90天及以上，入灰名单
     * @param dtoSrc
     */
    public void handleProjectToBlacklist(TradeBatchTransOrderDTO dtoSrc){
        if (BatchRefundTypeEnum.NEED_GUARANTEE_REFUND.getValue().equals(dtoSrc.getBatchRefundType())
                && RepaymentUtil.getOverdueDay(dtoSrc.getRefundDate(), new Date()) >= 30) {
            // 加灰名单
            Project project = projectMapperExt.selectByPrimaryKey(dtoSrc.getProjectId());

            BlackListStorageMQDTO blackListStorage = new BlackListStorageMQDTO();
            if (RepaymentUtil.getOverdueDay(dtoSrc.getRefundDate(), new Date()) >= 90) {
                blackListStorage.setListType((byte) 1);//黑名单
            }else{
                blackListStorage.setListType((byte) 2);//灰名单
            }
            blackListStorage.setUserSource((byte)3);//贷后还款
            try {
                blackListStorage.setIdCard(privacyMasks.decryptPrivacy(project.getBorrowIdCard()));
                blackListStorage.setMobileNo(privacyMasks.decryptPrivacy(project.getBorrowMobile()));
            }catch (Exception e ){
                log.error("refund for blacklist,des mobile and idcard Exception,",e);
            }
            rabbitTemplate.convertAndSend(MqConstant.BLACK_LIST_STORAGE_EXCHANGE, MqConstant.BLACK_LIST_STORAGE_ROUTE, blackListStorage);

        }
    }

}
